package edu.base.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.thymeleaf.util.DateUtils;

import com.fasterxml.jackson.annotation.JsonCreator.Mode;

import edu.base.model.Users;
import edu.base.service.UsersService;
import edu.base.util.JsonResults;
import edu.base.util.PageUtil;
import edu.base.config.CmsConfig;
import edu.base.model.CatDetail;
import edu.base.model.Category;
import edu.base.model.CmtJoinUser;
import edu.base.model.EchartStat;
import edu.base.model.MaintenanceRecord;
import edu.base.model.MaintenanceRecordJoinUsers;
import edu.base.model.Statistics;
import edu.base.service.CatDetailService;
import edu.base.service.CategoryService;
import edu.base.service.CmtService;
import edu.base.service.MaintenanceRecordService;

@Controller
@RequestMapping("/admin")
public class AdminController {
	final static org.slf4j.Logger log = LoggerFactory.getLogger(AdminController.class);

	@Autowired
	UsersService usersService; 
	@Autowired
	CategoryService categoryService;
	@Autowired
	CatDetailService catDetailService;
	@Autowired
	MaintenanceRecordService maintenanceRecordService;
	@Autowired
	CmtService cmtService;
	
	@RequestMapping("index")
	public String index() {
		return "/admin/index";
	}

	@RequestMapping("welcome")
	public String welcome() {
		return "/admin/welcome";
	}

	@RequestMapping(value = "user/lst")

	public String userLst(Integer r,String name,String tel,
						  Integer p, Model model) {
		if (p == null) {
			p = 1;
		}
		if(name == null) {
			name="";
		}
		if(tel == null) {
			tel = "";
		}
		List<Users> lst = usersService.query(r, name,tel, p, 5);
		Integer count = usersService.count(r,name,tel);
		PageUtil page = new PageUtil(5, count, p,
				"/admin/user/lst?r=" + r + "&name=" + name + "&tel=" + tel);
		log.error("count:" + count);
		
		model.addAttribute("page", page.page());
		model.addAttribute("list", lst);
		model.addAttribute("name", name);
		model.addAttribute("r", r);
		model.addAttribute("tel", tel);
		return "admin/user/lst";
	}

	/**
	 * 用户新新增
	 * 
	 * @param error
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "user/add")
	public String userAdd(String error, Integer r, Model model) throws UnsupportedEncodingException {
		if (error != null) {
			model.addAttribute("error", URLDecoder.decode(error, "utf-8"));
		}
		model.addAttribute("r", r);
		return "admin/user/add";
	}

	/**
	 * 用户添加
	 * 
	 * @param user
	 * @param r
	 * @param cls
	 * @param redirectAttributes
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "user/do_add")
	public String userDoAdd(Users user, Integer r,MultipartFile avatar_file, RedirectAttributes redirectAttributes)
			throws IllegalStateException, IOException {
		log.info("新增会员:" + user.toString());

		if (usersService.findByLoginName(user.getLoginName()) != null) {
			redirectAttributes.addAttribute("error",
					URLEncoder.encode("用户已存在", "utf-8"));
			return "redirect:/admin/user/add";
		}
		log.error("新增会员:" + avatar_file);
		if (!avatar_file.isEmpty()) {
			String savePath = CmsConfig.getUploadPath();
			String fileName = avatar_file.getOriginalFilename();
			String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			String saveName = System.currentTimeMillis() + ext;
			File saveFile = new File(savePath + saveName);
			log.info("save_name:" + saveFile.getAbsolutePath());
			avatar_file.transferTo(saveFile);
			user.setAvatar("/images/" + saveName);
		}
		
		usersService.insert(user);

		return "redirect:/admin/user/lst?r="+user.getRole();
	}
	
	
	@RequestMapping(value = "user/edit")
	public String userEdit(Integer id, Model model, String error) throws UnsupportedEncodingException {
		if (error != null) {
			model.addAttribute("error", URLDecoder.decode(error, "utf-8"));
		}
		Users user = usersService.findByKey(id);
		model.addAttribute("item", user);
		return "admin/user/edit";
	}
	/**
	 * 用户修改表单处理
	 * @param id
	 * @param loginPwd
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "user/update")
	public String userUpdate(Integer id, String loginPwd, Model model) {
		log.info("id:" + id);
		log.info("loginPwd" + loginPwd);
		if (id == 1) {
			log.error("权限不足，修改会员信息失败");
			return "redirect:/admin/user/edit";
		}

		// todo 限定参数
		Users user = new Users();
		user.setUserId(id);
		user.setLoginPwd(loginPwd);

		log.info("修改信息：" + user.toString());
		usersService.update(user);
		user = usersService.findByKey(id);
		return "redirect:/admin/user/lst?r=" + user.getRole();
	}
	
	
	@RequestMapping("user/lg")
	public String userLg(Integer id,Integer r) {
		
		Users user = new Users();
		user.setUserId(id);
		user.setState(0);
		usersService.update(user);
		
		return "redirect:/admin/user/lst?r=" + r;
	}
	
	@RequestMapping("user/fg")
	public String userFg(Integer id,Integer r) {
		Users user = new Users();
		user.setUserId(id);
		user.setState(1);
		usersService.update(user);
		
		return "redirect:/admin/user/lst?r=" + r;
	}
	
	@RequestMapping("user/del")
	@ResponseBody
	public JsonResults userDel(Integer id) {
		JsonResults res = new JsonResults();
		if(id == 1) {
			res.setResult_msg("管理员不能删除");
		}else {
			usersService.del(id);
		}
		
		return res;
	}
	
	
	/**
	 * 分类列表
	 * @param model
	 * @return
	 */
	@RequestMapping("cat/lst")
	public String catLst(Integer pid,Model model) {
		List<Category> lst = categoryService.query(pid);
		model.addAttribute("pid", pid);
		model.addAttribute("list", lst);
		return "admin/cat/lst";
	}
	/**
	 * 分类新增
	 * @return
	 */
	@RequestMapping("cat/add")
	public String catAdd(Integer pid,Model model) {
		model.addAttribute("pid", pid);
		return "admin/cat/add";
	}
	/**
	 * 分类新增 表单处理
	 * @param item
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("cat/do_add")
	public String catDoAdd(Category item, MultipartFile avatar_file) throws IllegalStateException, IOException {
		if (!avatar_file.isEmpty()) {
			String savePath = CmsConfig.getUploadPath();
			String fileName = avatar_file.getOriginalFilename();
			String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			String saveName = System.currentTimeMillis() + ext;
			File saveFile = new File(savePath + saveName);
			log.info("save_name:" + saveFile.getAbsolutePath());
			avatar_file.transferTo(saveFile);
			item.setCatThumb("/images/" + saveName);
		}
		categoryService.insert(item);
		return "redirect:/admin/cat/lst?pid=" + item.getPid();
	}
	/**
	 * 分类修改页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("cat/edit")
	public String catEdit(Integer id,Model model) {
		Category item = categoryService.findByKey(id);
		model.addAttribute("item", item);
		return "admin/cat/edit";
	}
	/**
	 * 分类修改，表单处理
	 * @param item
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("cat/update")
	public String catUpdate(Category item, MultipartFile avatar_file) throws IllegalStateException, IOException {
		if (!avatar_file.isEmpty()) {
			String savePath = CmsConfig.getUploadPath();
			String fileName = avatar_file.getOriginalFilename();
			String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			String saveName = System.currentTimeMillis() + ext;
			File saveFile = new File(savePath + saveName);
			log.info("save_name:" + saveFile.getAbsolutePath());
			avatar_file.transferTo(saveFile);
			item.setCatThumb("/images/" + saveName);
		}
		categoryService.update(item);
		return "redirect:/admin/cat/lst?pid=" + item.getPid();
	}
	/**
	 * 分类删除u
	 * @param id
	 * @return
	 */
	@RequestMapping("cat/del")
	public String catDel(Integer id,Integer pid) {
		categoryService.del(id);
		return "redirect:/admin/cat/lst?pid=" + pid;
	}
	
	
	@RequestMapping("catDetail/lst")
	public String catDetailLst(Integer catId,Model model,Integer state,String formType,Integer p) {
		if(p == null) {
			p = 1;
		}
		
		List<CatDetail> lst = catDetailService.find2(formType, catId, state, false, null, p, 5);
		Integer count = catDetailService.count2(formType, catId, state, false, null);
		log.error("count:" + count);
		
		String url =  "/admin/catDetail/lst?catId=" + catId;
		if(state != null) {
			url += "&state=" + state;
		}
		if(formType != null) {
			url += "&formType=" + formType;
		}
		
		PageUtil page = new PageUtil(5, count, p, url);
		
		model.addAttribute("page", page.page());
		model.addAttribute("list", lst);
		model.addAttribute("catId", catId);
		model.addAttribute("state", state);
		model.addAttribute("formType", formType);
		return "/admin/catDetail/lst";
	}
	
	@RequestMapping("catDetail/add")
	public String catDetailAdd(Integer catId,Model model) {
		model.addAttribute("catId", catId);
		return "admin/catDetail/add";
	}
	
	@RequestMapping("catDetail/do_add")
	public String catDetailDoAdd(CatDetail item,Integer count) {
		for(int x =0 ; x < count; x++) {
			catDetailService.insert(item);
		}
		List<CatDetail> lst = catDetailService.find(item.getCatId(), 1, false, null);
		Category cat = categoryService.findByKey(item.getCatId());
		cat.setCurCount(lst.size());
		categoryService.update(cat);
		return "redirect:/admin/cat/lst?pid=" + cat.getPid();
	}
	
	@RequestMapping("catDetail/baofei")
	public String catDetailBaofei(Integer id,Integer catId) {
		CatDetail item = new CatDetail();
		item.setDetailId(id);
		item.setState(0);
		catDetailService.update(item);
		
		Category cat = categoryService.findByKey(catId);
		List<CatDetail> lst = catDetailService.find(catId, 1, false, null);
		cat.setCurCount(lst.size());
		categoryService.update(cat);
		return "redirect:/admin/catDetail/lst?catId=" + catId;
	}
	
	
	@RequestMapping("record/lst")
	public String recordLst(Integer recordId,Integer p,String startDate, String endDate,Integer state,Integer workerId,Integer customerId,Model model,HttpSession session) throws ParseException {

		
		Date date1=null;
		Date date2 = null;
		if(startDate != null && startDate.length() > 0) {
			date1 = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
		}
		if(endDate != null&& endDate.length() > 0) {
			date2 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
		}
		if(p == null) {
			p = 1;
		}
		List<MaintenanceRecordJoinUsers> list = new ArrayList<MaintenanceRecordJoinUsers>();
		if(recordId != null) {
			return "redirect:/admin/record/detail?id=" + recordId;
		}
		
		list = maintenanceRecordService.query(date1, date2, customerId, workerId, state, p, 5);
		Integer count = maintenanceRecordService.count(date1, date2, customerId, workerId, state);
		log.error("count:" + count);
		String url = "/admin/record/lst?";
		if(recordId!=null) {
			url += "&recordId=" + recordId;
		}
		if(startDate != null) {
			url += "&startDate=" + startDate;
		}
		if(endDate != null) {
			url += "&endDate=" + endDate;
		}
		if(state != null) {
			url += "&state=" + state;
		}
		if(customerId != null) {
			url += "&customerId=" + customerId;
		}
		if(workerId != null) {
			url += "&workerId=" + workerId;
		}
		PageUtil page = new PageUtil(5, count, p, url);
		model.addAttribute("page", page.page());
		
		model.addAttribute("list", list);
		model.addAttribute("p", p);
		model.addAttribute("startDate",startDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("state", state);
		model.addAttribute("customerId", customerId);
		model.addAttribute("workerId", workerId);
		model.addAttribute("recordId", recordId);
		model.addAttribute("page", page.page());
		
		model.addAttribute("userId",(Integer)session.getAttribute("user_id"));
		log.debug("userId:" + session.getAttribute("user_id"));
		return "/admin/record/lst";
	}
	
	@RequestMapping("record/detail")
	public String RecordDetail(Integer id,HttpSession session,Model model) {
		MaintenanceRecord item = maintenanceRecordService.findByKey(id);
		List<CatDetail> lst = catDetailService.find(null, null, false, id);
		List<CmtJoinUser> cmtLst = cmtService.topicCmt(id);
		
		model.addAttribute("cmt_lst", cmtLst);
		model.addAttribute("lst", lst);
		model.addAttribute("item", item);
		return "/admin/record/detail";
	}
	
	
	@RequestMapping("cmt/del")
	@ResponseBody
	public JsonResults RecordDel(Integer cmtId) {
		cmtService.del(cmtId);
		JsonResults res = new JsonResults();
		return res;
	}
	
	@RequestMapping("record/stat")
	public String recordStat() {
		return "/admin/record/stat";
	}
	
	@RequestMapping("record/stat_ajax")
	@ResponseBody
	public JsonResults recordStatAjax(Integer year) {
		JsonResults res = new JsonResults();
		Map<String,Object> map = new HashMap<String,Object>();
		List<Statistics> lst = maintenanceRecordService.stat(year);
		List<String> lst1 = new ArrayList<String>();
		List<Integer> lst2 = new ArrayList<Integer>();
		for(int x =0 ; x < lst.size();x++) {
			lst1.add(lst.get(x).getM() + "月");
			lst2.add(lst.get(x).getC());
		}
		map.put("lst1", lst1);
		map.put("lst2", lst2);
		res.setResult_arr(map);
		return res;
	}
	
	@RequestMapping("user/stat")
	public String userStat() {
		return "/admin/user/stat";
	}
	
	@RequestMapping("user/stat_ajax")
	@ResponseBody
	public JsonResults userStatAjax(Integer year) {
		JsonResults res = new JsonResults();
		Map<String,Object> map = new HashMap<String,Object>();
		List<Statistics> lst = usersService.stat(year);
		log.error("userstat, lst.size:" + lst.size());
		List<String> lst1 = new ArrayList<String>();
		List<Integer> lst2 = new ArrayList<Integer>();
		for(int x =0 ; x < lst.size();x++) {
			lst1.add(lst.get(x).getM() + "月");
			lst2.add(lst.get(x).getC());
		}
		map.put("lst1", lst1);
		map.put("lst2", lst2);
		res.setResult_arr(map);
		return res;
	}

	
	@RequestMapping("user/user_edit")
	public String userEdit(Model model, Integer id) {
		edu.base.model.Users user = usersService.findByKey(id);
		model.addAttribute("user", user);
		return "/admin/user/user_edit";
	}
	
	@RequestMapping("user/do_user_edit")
	public String doUserEdit(Integer userId,String login_pwd, MultipartFile avatar,
							 String nick, String email,String tel, HttpSession session)
			throws IllegalStateException, IOException {
		log.info("用户信息修改 参数：" + login_pwd + avatar);
		Users user = new Users();
		user.setLoginPwd(login_pwd);
		if(!avatar.isEmpty()) {
			String savePath = CmsConfig.getUploadPath();
	    	String fileName = avatar.getOriginalFilename();
	    	String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
	    	String saveName = System.currentTimeMillis() + ext;
	    	File saveFile = new File(savePath + saveName);
	    	log.info("save_name:" + saveFile.getAbsolutePath());
	    	avatar.transferTo(saveFile);
	    	user.setAvatar("/images/" + saveName);
    	}
		user.setUserId(userId);
		user.setNick(nick);
		user.setEmail(email);
		user.setTel(tel);
		
		log.info("用户信息修改：" + user.toString());
		usersService.update(user);
		user = usersService.findByKey(user.getUserId());
		session.setAttribute("user", user);
		return "redirect:/admin/user/user_edit?id=" + userId;
	}
	
	
	@RequestMapping("cat/stat")
	public String catStat() {
		return "admin/cat/stat";
	}
	
	
	@RequestMapping("cat/stat_ajax")
	@ResponseBody
	public JsonResults catStatAjax() {
		JsonResults res = new JsonResults();
		Map<String,Object> map = new HashMap<String,Object>();
		List<Statistics> lst = categoryService.stat();
		List<String> lst1 = new ArrayList<String>();
		List<EchartStat> lst2 = new ArrayList<EchartStat>();
		for(int x =0 ; x < lst.size();x++) {
			EchartStat item = new EchartStat();
			item.setName(lst.get(x).getN());
			item.setValue(lst.get(x).getC());
			lst2.add(item);
			lst1.add(lst.get(x).getN());
		}
		map.put("lst1", lst1);
		map.put("lst", lst2);
		res.setResult_arr(map);
		return res;
	}
	
	@RequestMapping("record/stat_device")
	public String recordStatDevice() {
		return "admin/record/device_stat";
	}
	
	@RequestMapping("record/stat_device_ajax")
	@ResponseBody
	public JsonResults recordStatDeviceAjax(Integer year) {
		JsonResults res = new JsonResults();
		Map<String,Object> map = new HashMap<String,Object>();
		List<Statistics> lst = maintenanceRecordService.statByDeviceType(year);
		List<String> lst1 = new ArrayList<String>();
		List<EchartStat> lst2 = new ArrayList<EchartStat>();
		for(int x =0 ; x < lst.size();x++) {
			EchartStat item = new EchartStat();
			item.setName(lst.get(x).getN());
			item.setValue(lst.get(x).getC());
			lst2.add(item);
			lst1.add(lst.get(x).getN());
		}
		map.put("lst1", lst1);
		map.put("lst", lst2);
		res.setResult_arr(map);
		return res;
	}
	
	
	@RequestMapping("catDetail/stat")
	public String catDetailStatDevice() {
		return "admin/catDetail/stat";
	}
	
	@RequestMapping("catDetail/stat_ajax")
	@ResponseBody
	public JsonResults catDetailStatAjax(Integer year) {
		JsonResults res = new JsonResults();
		Map<String,Object> map = new HashMap<String,Object>();
		List<Statistics> lst = catDetailService.stat(year);
		List<String> lst1 = new ArrayList<String>();
		List<EchartStat> lst2 = new ArrayList<EchartStat>();
		for(int x =0 ; x < lst.size();x++) {
			EchartStat item = new EchartStat();
			item.setName(lst.get(x).getN());
			item.setValue(lst.get(x).getC());
			lst2.add(item);
			lst1.add(lst.get(x).getN());
		}
		map.put("lst1", lst1);
		map.put("lst", lst2);
		res.setResult_arr(map);
		return res;
	}
	
}
